import logging

from absl import app
from tornado.ioloop import IOLoop

import coin.flow.subscriber as flow_subscriber
from coin.flow.simple_queue import SimpleQueue
from coin.strategy.mm.base.multi_feed_subsystem import MultiFeedSubsystem

from coin.exchange.upbit_v1.kr_rest.product import UpbitProduct
from coin.exchange.okex.kr_rest.product import OkexProduct
import experimental.prophet as prophet


def model(coins):
  ts = prophet.global_timestamp()

  books_1 = []
  books_2 = []
  for coin in coins:
    product_1 = UpbitProduct.FromStr('%s-KRW' % coin)
    feed_1 = prophet.fastfeed_coin(product_1, 'Spot.Upbit')
    books_1 += [prophet.book(feed_1)]

    product_2 = OkexProduct.FromStr('%s-USDT' % coin)
    feed_2 = prophet.fastfeed_coin(product_2, 'Spot.Okex.v3')
    books_2 += [prophet.book(feed_2)]

  usdkrw_rate = 1210.
  premiums = []
  for coin, book_1, book_2 in zip(coins, books_1, books_2):
    mid_p_1 = (book_1.ask0.price + book_1.bid0.price) / 2. / usdkrw_rate
    mid_p_2 = (book_2.ask0.price + book_2.bid0.price) / 2.
    premiums += [(mid_p_1 / mid_p_2).named_ref('premium_%s' % coin)]

  min_premium = prophet.min(*premiums).named_ref('min_premium')
  max_premium = prophet.max(*premiums).named_ref('max_premium')
  premium_diff = (max_premium - min_premium).named_ref('premium_diff')

  prophet.printer('%t %s bp --- BTC:%s ETH:%s XRP:%s BCH:%s LTC:%s EOS:%s',
                  ts,
                  premium_diff * 10000.,
                  *premiums)


def main(argv):
  ioloop = IOLoop.current()
  queue = SimpleQueue('queue')
  flow_sub = flow_subscriber.from_queue(queue)

  g = prophet.Graph()
  with prophet.as_default_graph(g):
    coins = ['BTC', 'ETH', 'XRP', 'BCHABC', 'LTC', 'EOS']
    model(coins)

  # print(g.dump_dot())

  adapter = prophet.FastfeedGraphAdapter(g, '')
  feed_sub_req = adapter.get_feed_sub_requests()

  feed_subsystem = MultiFeedSubsystem()
  feed_subsystem.subscribe_fastfeed(feed_sub_req, adapter.on_book_reset)
  feed_subsystem.start(ioloop, queue, flow_sub)

  try:
    ioloop.start()
    return 0
  except KeyboardInterrupt:
    return 1


if __name__ == '__main__':
  logging.basicConfig(level='DEBUG')
  app.run(main)
